<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--测试组件-->
    <div>
      <ElCascader
        v-model="value"
        :options="pageData"
        :props="{ label: 'name', value: 'id', multiple: false, checkStrictly: false }"
      ></ElCascader>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['factory:clothing-category:add']"
          type="success"
          @click="handleOpenDialog('0')"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['factory:clothing-category:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        row-key="id"
        border
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="分类ID" prop="id" min-width="150" align="center" />
        <el-table-column
          key="parentId"
          label="父节点ID"
          prop="parentId"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="treePath"
          label="父节点路径"
          prop="treePath"
          min-width="150"
          align="center"
        />
        <el-table-column key="name" label="分类名称" prop="name" min-width="150" align="center" />
        <el-table-column key="sort" label="排序" prop="sort" min-width="150" align="center" />
        <el-table-column label="显示状态(0:隐藏, 1:显示)" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.visible" code="visible_status" />
          </template>
        </el-table-column>
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['factory:clothing-category:add']"
              type="primary"
              link
              size="small"
              icon="plus"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              新增
            </el-button>
            <el-button
              v-hasPerm="['factory:clothing-category:edit']"
              type="primary"
              size="small"
              link
              @click.stop="handleOpenDialog(undefined, scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['factory:clothing-category:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 服装分类表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级菜单"
            :data="categoryOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="分类名称" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="排序" />
        </el-form-item>

        <el-form-item prop="visible" label="显示状态">
          <el-radio-group v-model="formData.visible">
            <el-radio :value="1">显示</el-radio>
            <el-radio :value="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ClothingCategory",
  inheritAttrs: false,
});

import ClothingCategoryAPI, {
  ClothingCategoryPageVO,
  ClothingCategoryForm,
  ClothingCategoryPageQuery,
} from "@/api/factory/clothing-category";

const value = ref(null);

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ClothingCategoryPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 服装分类表格数据
const pageData = ref<ClothingCategoryPageVO[]>([]);

// 顶级分类下拉选项
const categoryOptions = ref<OptionType[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 服装分类表单数据
const formData = reactive<ClothingCategoryForm>({});

// 服装分类表单校验规则
const rules = reactive({
  id: [{ required: true, message: "请输入分类ID", trigger: "blur" }],
  parentId: [{ required: true, message: "请输入父节点ID", trigger: "blur" }],
  treePath: [{ required: true, message: "请输入父节点路径", trigger: "blur" }],
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  visible: [{ required: true, message: "请输入显示状态(0:隐藏, 1:显示)", trigger: "blur" }],
  createTime: [{ required: true, message: "请输入创建时间", trigger: "blur" }],
  updateTime: [{ required: true, message: "请输入更新时间", trigger: "blur" }],
});

/** 查询服装分类 */
// function handleQuery() {
//   loading.value = true;
//   ClothingCategoryAPI.getPage(queryParams)
//     .then((data) => {
//       pageData.value = data.list;
//       total.value = data.total;
//     })
//     .finally(() => {
//       loading.value = false;
//     });
// }

/**查询服装分类树形数据*/
function handleQuery() {
  loading.value = true;
  ClothingCategoryAPI.getTree(queryParams)
    .then((data) => {
      pageData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置服装分类查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开服装分类弹窗 */
// function handleOpenDialog(id?: number) {
//   dialog.visible = true;
//   if (id) {
//     dialog.title = "修改服装分类";
//     ClothingCategoryAPI.getFormData(id).then((data) => {
//       Object.assign(formData, data);
//     });
//   } else {
//     dialog.title = "新增服装分类";
//   }
// }

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function handleOpenDialog(parentId?: string, menuId?: string) {
  console.log("parentId", parentId);
  ClothingCategoryAPI.getOptions(true)
    .then((data) => {
      categoryOptions.value = [{ value: "0", label: "顶级菜单", children: data }];
    })
    .then(() => {
      dialog.visible = true;
      if (menuId) {
        dialog.title = "编辑菜单";
        ClothingCategoryAPI.getFormData(menuId).then((data) => {
          // initialMenuFormData.value = { ...data };
          Object.assign(formData, data);
          console.log({ ...formData }, "we3ewweo");
        });
      } else {
        dialog.title = "新增菜单";
        formData.parentId = parentId?.toString();
      }
    });
}

/** 提交服装分类表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ClothingCategoryAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ClothingCategoryAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭服装分类弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除服装分类 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ClothingCategoryAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
